<template>
  <el-card class="table-card">
    <el-table 
      :data="displayData" 
      v-loading="loading" 
      style="width: 100%" 
      border
      @selection-change="$emit('selection-change', $event)"
    >
      <el-table-column type="selection" width="55" resizable />
      <el-table-column prop="name" label="任务名称" min-width="150" resizable>
        <template #default="scope">
          <span v-if="scope.row.name">{{ scope.row.name }}</span>
          <span v-else class="text-gray-400">未设置</span>
        </template>
      </el-table-column>
      <el-table-column prop="course.name" label="课程名称" min-width="120" resizable />
      <el-table-column prop="term.name" label="学期" width="100" resizable />
      <el-table-column prop="major.name" label="专业" width="120" resizable />
      <el-table-column prop="cengCi.name" label="培养层次" width="100" resizable />
      <el-table-column label="授课教师" min-width="180" resizable>
        <template #default="scope">
          <div v-if="scope.row.teachers && scope.row.teachers.length > 0" class="teachers-info">
            <div class="teachers-list">
              <div 
                v-for="(teacher, index) in getSortedTeachers(scope.row.teachers)" 
                :key="teacher.id" 
                class="teacher-item"
              >
                <span class="teacher-name">{{ teacher.name }}</span>
                <el-tag 
                  v-if="teacher.isPrimary" 
                  type="primary" 
                  size="small" 
                  effect="dark"
                  class="primary-tag"
                >
                  主讲
                </el-tag>
                <span v-if="index < getSortedTeachers(scope.row.teachers).length - 1" class="separator">、</span>
              </div>
            </div>
            <el-button 
              v-if="canManageTeachers(scope.row)" 
              size="small" 
              type="info" 
              text 
              @click="$emit('manage-teachers', scope.row)"
              class="manage-btn"
            >
              <el-icon><Sort /></el-icon>
            </el-button>
          </div>
          <div v-else class="empty-teachers">
            <span class="text-gray-400">未分配</span>
            <el-button 
              v-if="canManageTeachers(scope.row)" 
              size="small" 
              type="primary" 
              text 
              @click="$emit('assign-teachers', scope.row)"
            >
              分配教师
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="学员人数" width="80" resizable>
        <template #default="scope">
          <el-tag size="small">{{ scope.row.studentCount || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总结状态" width="120" resizable>
        <template #default="scope">
          <el-tag 
            :type="getSummaryStatusType(scope.row.summaryStatus)" 
            size="small"
          >
            {{ getSummaryStatusText(scope.row.summaryStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right" resizable>
        <template #default="scope">
          <el-button size="small" type="primary" @click="$emit('manage-scores', scope.row)">
            <el-icon><EditPen /></el-icon> 成绩管理
          </el-button>
          <el-button 
            size="small" 
            :type="getSummaryButtonType(scope.row)" 
            @click="handleSummaryClick(scope.row)"
          >
            <el-icon><Document /></el-icon> {{ getSummaryButtonText(scope.row) }}
          </el-button>
          <!-- 移除了更多下拉菜单，因为所有功能都已整合到主按钮中 -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        :current-page="pagination.current || 1"
        :page-size="pagination.pageSize || 10"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total || 0"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="$emit('size-change', $event)"
        @current-change="$emit('current-change', $event)"
      />
    </div>
  </el-card>
</template>

<script>
import { computed } from 'vue'
import { EditPen, Document, ArrowDown, Plus, View, Link, Sort } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

export default {
  name: 'FrontendTeachingMissionTable',
  components: {
    EditPen,
    Document,
    ArrowDown,
    Plus,
    View,
    Link,
    Sort
  },
  props: {
    tableData: {
      type: Array,
      default: () => []
    },
    paginatedData: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    pagination: {
      type: Object,
      default: () => ({
        current: 1,
        pageSize: 10,
        total: 0
      })
    }
  },
  emits: [
    'selection-change',
    'manage-scores',
    'write-summary',
    'modify-summary',
    'view-summary',
    'dropdown-command',
    'size-change',
    'current-change',
    'manage-teachers',
    'assign-teachers'
  ],
  setup(props, { emit }) {
    const userStore = useUserStore()

    // 统一数据源：优先使用 paginatedData，否则使用 tableData
    const displayData = computed(() => {
      return props.paginatedData.length > 0 ? props.paginatedData : props.tableData
    })

    /**
     * 获取总结状态的标签类型
     * @param {number} status 状态值
     * @returns {string} ElementUI标签类型
     */
    const getSummaryStatusType = (status) => {
      switch (status) {
        case 0:
          return 'info' // 灰色 - 未创建
        case 1:
          return 'warning' // 黄色 - 未提交
        case 2:
          return 'primary' // 蓝色 - 已提交
        case 3:
          return 'success' // 绿色 - 已教研室审核通过
        case 4:
          return 'success' // 绿色 - 已部系审核通过
        case 5:
          return 'danger' // 红色 - 教研室审核未通过
        case 6:
          return 'danger' // 红色 - 部系审核未通过
        default:
          return 'info' // 默认使用info类型
      }
    }

    /**
     * 获取总结状态的文本描述
     * @param {number} status 状态值
     * @returns {string} 状态文本
     */
    const getSummaryStatusText = (status) => {
      switch (status) {
        case 0:
          return '未创建'
        case 1:
          return '未提交'
        case 2:
          return '已提交'
        case 3:
          return '教研室已通过'
        case 4:
          return '部系已通过'
        case 5:
          return '教研室未通过'
        case 6:
          return '部系未通过'
        default:
          return '未知状态'
      }
    }

    /**
     * 检查当前用户是否是该教学任务的第一主讲教师
     * @param {Object} row 教学任务行数据
     * @returns {boolean} 是否是第一主讲教师
     */
    const isCurrentUserOwner = (row) => {
      if (!row.teachers || !row.teachers.length) return false
      
      // 按排序获取教师列表
      const sortedTeachers = getSortedTeachers(row.teachers)
      if (!sortedTeachers.length) return false
      
      // 找到第一个主讲教师
      const firstPrimaryTeacher = sortedTeachers.find(teacher => teacher.isPrimary)
      
      // 如果有主讲教师，检查是否是当前用户
      if (firstPrimaryTeacher) {
        return firstPrimaryTeacher.id === userStore.userId
      }
      
      // 如果没有设置主讲教师，则默认第一个教师为主讲
      return sortedTeachers[0].id === userStore.userId
    }

    /**
     * 获取总结按钮的文本
     * @param {Object} row 教学任务行数据
     * @returns {string} 按钮文本
     */
    const getSummaryButtonText = (row) => {
      const isOwner = isCurrentUserOwner(row)
      const status = row.summaryStatus

      // 如果当前用户拥有该任务且没有教学总结（状态为0），显示"填写总结"
      if (isOwner && status === 0) {
        return '填写总结'
      }
      
      // 如果教学总结状态为未提交(1)或被拒绝(5,6)，显示"修改总结"
      if (isOwner && (status === 1 || status === 5 || status === 6)) {
        return '修改总结'
      }
      
      // 其他情况显示"查看总结"
      return '查看总结'
    }

    /**
     * 获取总结按钮的类型
     * @param {Object} row 教学任务行数据
     * @returns {string} 按钮类型
     */
    const getSummaryButtonType = (row) => {
      const isOwner = isCurrentUserOwner(row)
      const status = row.summaryStatus

      // 填写总结或修改总结时使用warning类型
      if (isOwner && (status === 0 || status === 1 || status === 5 || status === 6)) {
        return 'warning'
      }
      
      // 查看总结时使用success类型
      return 'success'
    }

    /**
     * 处理总结按钮点击事件
     * @param {Object} row 教学任务行数据
     */
    const handleSummaryClick = (row) => {
      const isOwner = isCurrentUserOwner(row)
      const status = row.summaryStatus

      if (isOwner && status === 0) {
        // 填写总结
        emit('write-summary', row)
      } else if (isOwner && (status === 1 || status === 5 || status === 6)) {
        // 修改总结
        emit('modify-summary', row)
      } else {
        // 查看总结
        emit('view-summary', row)
      }
    }

    /**
     * 获取按排序顺序排列的教师列表
     * @param {Array} teachers 教师列表
     * @returns {Array} 排序后的教师列表
     */
    const getSortedTeachers = (teachers) => {
      if (!teachers || !Array.isArray(teachers)) return []
      
      return [...teachers].sort((a, b) => {
        // 首先按 sortOrder 排序，如果没有则按原始顺序
        const orderA = a.sortOrder || 999
        const orderB = b.sortOrder || 999
        if (orderA !== orderB) {
          return orderA - orderB
        }
        
        // 如果排序号相同，主要教师排在前面
        if (a.isPrimary && !b.isPrimary) return -1
        if (!a.isPrimary && b.isPrimary) return 1
        
        return 0
      })
    }

    /**
     * 检查当前用户是否可以管理教师
     * @param {Object} row 教学任务行数据
     * @returns {boolean} 是否可以管理教师
     */
    const canManageTeachers = (row) => {
      // 管理员或教研室管理员可以管理教师
      const userRoles = userStore.roles || []
      return userRoles.includes('ADMIN') || 
             userRoles.includes('RESEARCH_OFFICE_ADMIN') ||
             userRoles.includes('DEPARTMENT_ADMIN')
    }

    return {
      displayData,
      getSummaryStatusType,
      getSummaryStatusText,
      getSummaryButtonText,
      getSummaryButtonType,
      handleSummaryClick,
      getSortedTeachers,
      canManageTeachers
    }
  }
}
</script>

<style scoped>
.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.text-gray-400 {
  color: #9ca3af;
}

/* 教师信息显示样式 */
.teachers-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.teachers-list {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 2px;
}

.teacher-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.teacher-name {
  font-weight: 500;
  color: #303133;
}

.primary-tag {
  font-size: 10px;
  height: 16px;
  line-height: 16px;
  padding: 0 4px;
}

.separator {
  color: #909399;
  margin: 0 2px;
}

.manage-btn {
  flex-shrink: 0;
  padding: 2px 4px;
  font-size: 12px;
}

.empty-teachers {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
